// ==UserScript==
// @name         missav_助手
// @namespace    http://tampermonkey.net/
// @version      0.1.2
// @description  try to take over the world!
// @author       You
// @match        https://missav.com/
// @match        https://123av.org/
// @match        https://pedavx.com/
// @match        https://ms606.com/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=missav.com
// @grant        wanyc
// @grant        GM_setClipboard
// @grant        GM_xmlhttpRequest
// @include      *://*missav*/*
// @include      *://*123av*/*
// @include      *://*pedavx*/*
// @include      *://*ms606*/*


// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    // alert("missav start!");
    var flexColStr = "xl:grid-cols-4";

    addTopPanel();
    addItemButtonPanel();
    addTitleBtn();
	guangGao();

    // ******************************************************************************************************************************************************
    //#region TopPanel
    function addTopPanel(){
        var ppp2 = document.createElement("p");
        ppp2.style.backgroundColor = "#eee";
        // ppp2.innerHTML = `
        //             <button onclick="loadMovieInfo()">加载</button>
        //             <button onclick="clearMovieAddrList()">清除</button>
        //            `;

        /* 查询播放地址 */
        var btnRight = document.createElement("button");
        btnRight.style.marginLeft = "50px";
        btnRight.style.marginRight = "10px";
        btnRight.appendChild(document.createTextNode("侧边栏扩大"));
        btnRight.addEventListener("click", changeWidthOfRight);
        ppp2.appendChild(btnRight);

        var btnMaxWidth = document.createElement("button");
        btnMaxWidth.style.marginLeft = "30px";
        btnMaxWidth.style.marginRight = "10px";
        btnMaxWidth.appendChild(document.createTextNode("增加宽度"));
        btnMaxWidth.addEventListener("click", changeWidthOfCenter);
        ppp2.appendChild(btnMaxWidth);

        var btnAVID = document.createElement("button");
        btnAVID.style.marginLeft = "30px";
        btnAVID.style.marginRight = "10px";
        btnAVID.appendChild(document.createTextNode("显示番号"));
        btnAVID.addEventListener("click", displayAVCode);
        ppp2.appendChild(btnAVID);

        /* 每行显示数 */
        var inputBoxNumber = document.createElement("input");
        inputBoxNumber.style.marginLeft = "50px";
        inputBoxNumber.style.marginRight = "5px";
        inputBoxNumber.style.width = "60px";
        inputBoxNumber.id = "page-row-number";
        inputBoxNumber.type = "number";
        inputBoxNumber.value = 3;
        ppp2.appendChild(inputBoxNumber);
		
        var btnBoxNumber = document.createElement("button");
        btnBoxNumber.style.marginLeft = "5px";
        btnBoxNumber.style.marginRight = "10px";
        btnBoxNumber.appendChild(document.createTextNode("每行显示数"));
        btnBoxNumber.addEventListener("click", changeRowNumber);
        ppp2.appendChild(btnBoxNumber);
		
		var addItemButton = document.createElement("button");
        addItemButton.style.marginLeft = "30px";
        addItemButton.style.marginRight = "10px";
        addItemButton.appendChild(document.createTextNode("item按钮"));
        addItemButton.addEventListener("click", addItemButtonPanel);
        ppp2.appendChild(addItemButton);
		
		var createVideoButton = document.createElement("button");
        createVideoButton.style.marginLeft = "30px";
        createVideoButton.style.marginRight = "10px";
        createVideoButton.appendChild(document.createTextNode("合成视频"));
        createVideoButton.addEventListener("click", function (){
			testCreateVideoFromImages();
		});
        ppp2.appendChild(createVideoButton);

        var submitThumbButton = document.createElement("button");
        submitThumbButton.style.marginLeft = "30px";
        submitThumbButton.style.marginRight = "10px";
        submitThumbButton.appendChild(document.createTextNode("提交预览"));
        submitThumbButton.addEventListener("click", function (){
            submitThumb();
        });
        ppp2.appendChild(submitThumbButton);

        /* 按钮面板 */
        var buttondiv = document.createElement("div");
        buttondiv.appendChild(ppp2);

        /* 插入到页面中 */
        var element = document.getElementsByClassName("fixed from-darkest")[0];
        if (element){
            element.parentNode.parentNode.insertBefore(buttondiv, element.parentNode);
			return ;
        }
		
		element = document.getElementsByClassName("fixed z-max")[0];
        if (element){
            element.parentNode.parentNode.insertBefore(buttondiv, element.parentNode);
			return ;
        }
    }

    function changeRowNumber() {
        var numberElement = document.getElementById("page-row-number");
        if (!numberElement) return;

        var number = parseInt(numberElement.value);

        var conEles = document.getElementsByClassName("grid grid-cols-2 gap-5");
        if (conEles.length > 0) {
            for(var i = 0; i < conEles.length; i++) {
                var conEle = conEles[i];

                // conEle.classList.remove("md:grid-cols-3");
                // conEle.classList.add("md:grid-cols-2");
                if (conEle.classList.contains(flexColStr)){
                    conEle.classList.remove(flexColStr);
                    var flexColStr2 = "xl:grid-cols-" + number;
                    conEle.classList.add(flexColStr2);
                }

            }
            flexColStr = "xl:grid-cols-" + number;
        }
    }

    function changeWidthOfRight() {
        var rightEles = document.getElementsByClassName("flex mb-6");
        if (rightEles.length > 0) {
            for(var i = 0; i < rightEles.length; i++) {
                var rightEle = rightEles[i];
                rightEle.classList.add("flex-col");
            }
        }

        var rightEles2 = document.getElementsByClassName("flex-none mr-4");
        if (rightEles2.length > 0){
            for(var j=0; j<rightEles2.length; j++){
                var rightEle2 = rightEles2[j];
                rightEle2.style.width = "300px";
            }
        }

        var rightEles3 = document.getElementsByClassName("flex-1");
        if (rightEles3.length > 0){
            for(var k=0; k<rightEles3.length; k++){
                var rightEle3 = rightEles3[k];
                rightEle3.style.width = "300px";
            }
        }
    }

    function changeWidthOfCenter(){
        var conEles = document.getElementsByClassName("sm:container");
        if (conEles.length > 0){
            for(var i=0; i<conEles.length; i++){
                var conEle = conEles[i];

                conEle.style.maxWidth = "1600px";
            }
        }
    }

    function displayAVCode(){
        let conEles = document.querySelectorAll(".max-h-14 a");
        if (conEles.length > 0){
            for(let i=0; i<conEles.length; i++){
                let conEle = conEles[i];

                let addr = conEle.href;
                let startIdx = addr.lastIndexOf("/");
                let endIdx = addr.lastIndexOf("#");
                if (startIdx < 0){
                    continue;
                }
                let avid = addr.slice(startIdx+1, endIdx).toUpperCase();
                let avid2 = avid.match(/[a-zA-z]{2,5}-?\d{2,5}/)?.at(0);
                if (!avid2) continue;

                let text = conEle.textContent;
                let code = text.match(/[a-zA-z]{2,5}-?\d{2,5}/)?.at(0);
                if (code) continue;

                conEle.textContent = avid + " " + text;

            }
        }

        displayAVCode02();
    }

    function displayAVCode02(){
        let conEles = document.querySelectorAll(".my-2 a");
        if (conEles.length > 0){
            for(let i=0; i<conEles.length; i++){
                let conEle = conEles[i];

                let addr = conEle.href;
                let startIdx = addr.lastIndexOf("/");
                let endIdx = addr.lastIndexOf("#");
                if (startIdx < 0 ){
                    continue;
                }
                let avid = addr.slice(startIdx+1, endIdx).toUpperCase();
                let avid2 = avid.match(/[a-zA-z]{2,5}-?\d{2,5}/)?.at(0);
                if (!avid2) continue;

                let text = conEle.textContent;
                let code = text.match(/[a-zA-z]{2,5}-?\d{2,5}/)?.at(0);
                if (code) continue;

                conEle.textContent = avid + " " + text;
            }
        }
    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region Items

    function addItemButtonPanel(){
        let add_div = document.querySelectorAll('.thumbnail.group');
        console.log(add_div);
        if(add_div){
            console.log(add_div.length);
            add_div.forEach(function (item, index) {
                // index就是索引值
                // console.log(index);
                // domEle表示获取遍历每一个dom对象
                // console.log(domEle);

                const domEle = item;

                let jumpBtn = document.createElement('a');
                //jumpBtn.className = "text-secondary group-hover:text-primary";
                jumpBtn.href = "javascript:void(0)";
                jumpBtn.textContent = "  【JDB】  ";
                jumpBtn.addEventListener("click", function (event){
                    let avid = getAVCode(domEle);
                    if (avid){
                        jumpJDB(avid);
                    }

                });

                let ciliBtn = document.createElement('a');
                //ciliBtn.className = "text-secondary group-hover:text-primary";
                ciliBtn.href = "javascript:void(0)";
                ciliBtn.textContent = "  【磁力】  ";
                ciliBtn.addEventListener("click", function (event){
                    let avid = getAVCode(domEle);
                    if (avid){
                        // ciliSreach(avid);

                        var ciliUrl = "https://xiongmaoto.top/?searchstr=" + avid;
                        // window.open(ciliUrl);
                        popupWindow(ciliUrl, 900, 1100);
                    }

                });

                let ciliBtn2 = document.createElement('a');
                //ciliBtn2.className = "text-secondary group-hover:text-primary";
                ciliBtn2.href = "javascript:void(0)";
                ciliBtn2.textContent = "  【磁力2】  ";
                ciliBtn2.addEventListener("click", function (event){
                    let titleStr = getAVCodeAll(domEle);
                    if (titleStr){
                        // ciliSreach(titleStr);

                        var ciliUrl = "https://xiongmaoto.top/?searchstr=" + titleStr;
                        // window.open(ciliUrl);
                        popupWindow(ciliUrl, 900, 1100);
                    }

                });

                let prewinBtn = document.createElement('a');
                //prewinBtn.className = "text-secondary group-hover:text-primary";
                prewinBtn.href = "javascript:void(0)";
                prewinBtn.textContent = "  【弹窗】  ";
                prewinBtn.addEventListener("click", function (){
                    // 弹出窗口的设置
                    const titleStr = getAVCodeAll(domEle);
                    var code = getAVCode(domEle);
                    var newUrl = 'http://localhost:10168/site/premovie/index.html?avcode=' + code + '&avtitle=' + titleStr;;
                    popupWindow(newUrl);
                });
				
				let longimgBtn = document.createElement('a');
                longimgBtn.href = "javascript:void(0)";
                longimgBtn.textContent = "  【长图】  ";
                longimgBtn.addEventListener("click", function (){
                    // 弹出窗口的设置
                    const titleStr = getAVCodeAll(domEle);
                    var code = getAVCode(domEle);
                    var newUrl = "https://blogjav.net/?s=" + code.toLowerCase() + "&jump=auto";
                    popupWindow(newUrl);
                });

                let buttonDiv = document.createElement("div");
                buttonDiv.className = "text-sm text-nord4";
                buttonDiv.appendChild(jumpBtn);
                buttonDiv.appendChild(prewinBtn);
				buttonDiv.appendChild(longimgBtn);
                buttonDiv.appendChild(ciliBtn);
                buttonDiv.appendChild(ciliBtn2);


                domEle.appendChild(buttonDiv);
            });
        }
    }

    function getAVCode(domEle){
        //let dbUrl = domEle.getElementsByTagName("a")[0].href;
        //let titleEle = domEle.querySelector('.my-2.text-sm.text-nord4.truncate a');
        let titleEle = domEle.querySelector('a');
        if (titleEle){
            // let strls = dbUrl.toString().split("/");
            // let avid = strls[strls.length-1];
            // let avid2 = avid.replace("-uncensored-leak", "");
            //
            // return avid2;

            // 使用正则表达式查找"/"和"#"之间的内容
            let dbUrl = titleEle.href;
            let regex = /\/([^/]*?)$/;
            if (/#/.test(dbUrl)){
                // 如果url结尾包含#
                regex = /\/([^/#]*?)#/;
            }
            let match = dbUrl.match(regex);
            if (match && match[1]) {
                let avid = match[1].replace("-uncensored-leak", "")
                    .replace("-chinese-subtitle", "")
					.replace("-english-subtitle", "");
                return avid;
            } else {
                // 如果没有找到匹配项，或者"/"和"#"之间没有字符，返回null或错误信息
                return null; // 或者 'No content between "/" and "#"'
            }
        }
        return null;
    }

    function getAVCodeAll(domEle){
        //let dbUrl = domEle.getElementsByTagName("a")[0].href;
        let titleEle = domEle.querySelector('.my-2.text-sm.text-nord4.truncate a');
		if (!titleEle && domEle.parentNode && domEle.parentNode.parentNode){
			titleEle = domEle.parentNode.parentNode.querySelector('.max-h-14.overflow-y-hidden.text-sm a');
		}
		
        if (titleEle){
            let avtitle = titleEle.textContent;

            return avtitle;
        }
        return null;
    }

    function ciliSreach(code){
        var newCode = code.replace("-", " ");
        GM_setClipboard(newCode);
        //var ciliUrl = "https://xiongmaoto.top/search?keyword=" + newCode + "&sos=relevance&sofs=all&sot=all&soft=all&som=exact&p=1";
        var ciliUrl = "https://xiongmaoto.top";
        window.open(ciliUrl);
    }

    function parseJdbUrl(targetUrl){
        let domain = getDomainFromUrl(targetUrl);

        fetch(targetUrl) // 请求用户指定的页面
            .then(response => response.text())
            .then(html => {
                console.log(html);
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const movieList = doc.getElementsByClassName('movie-list');
                if (movieList.length > 0) {
                    const firstElement = movieList[0];
                    const firstLink = firstElement.querySelector('a');
                    if (firstLink) {
                        const href = firstLink.getAttribute('href');

                        var fullUrl = "http://" + domain + href;

                        var newWindow = window.open(fullUrl, '_blank'); // 在新标签页中打开URL
                        // 可选：检查窗口是否成功打开
                        if (!newWindow) {
                            // 窗口可能被浏览器阻止了
                            alert('请允许浏览器打开新窗口或标签页。');
                        }
                    }
                }
            })
            .catch(err => console.error('Error fetching and parsing HTML', err));
    }

    function jumpJDB(avcode){
        // let jdbUrl = "https://javdb458.com/search?q=" + avcode + "&f=all";
        // parseJdbUrl(jdbUrl);

        let jdbUrl = "https://javdb458.com/search?q=" + avcode + "&f=all&jump=auto";
        window.open(jdbUrl, '_blank'); // 在新标签页中打开URL
    }

    function getDomainFromUrl(url) {
        // 创建一个新的URL对象
        const urlObj = new URL(url);
        // 使用hostname属性获取域名
        return urlObj.hostname;
    }

    function popupWindow(newUrl, width = 1420, height = 960){
        var left = (window.screen.width - width)/2;
        var top = (window.screen.height - height)/2;
        var popupWindow = window.open(newUrl, '_blank', `left=${left}, top=${top} width=${width}, height=${height}`);
        // popupWindow.location.href = newUrl;
    }

    //#endregion


    // ******************************************************************************************************************************************************
    //#region Title

    function addTitleBtn(){
        var buttonDiv = document.querySelector('.justify-center.space-x-4');
        if (buttonDiv){
            let jumpBtn = document.createElement('button');
            //jumpBtn.className = "text-secondary group-hover:text-primary";
            jumpBtn.href = "javascript:void(0)";
            jumpBtn.textContent = "  【JDB】  ";
            jumpBtn.addEventListener("click", function (event){
                let avid = getAVCode2();
                if (avid){
                    jumpJDB(avid);
                }

            });

            let ciliBtn = document.createElement('button');
            //ciliBtn.className = "text-secondary group-hover:text-primary";
            ciliBtn.href = "javascript:void(0)";
            ciliBtn.textContent = "  【磁力】  ";
            ciliBtn.addEventListener("click", function (event){
                let avid = getAVCode2();
                if (avid){
                    ciliSreach(avid);
                }

            });

            buttonDiv.appendChild(jumpBtn);
            buttonDiv.appendChild(ciliBtn);
        }
    }

    function getAVCode2(){
        let avtitle_h1 = document.querySelector('.mt-4 h1');
        if (avtitle_h1){
            let strls = avtitle_h1.textContent.split(" ");
            if (strls && strls[0]){
                let avid = strls[0];
                let avid2 = avid.replace("-uncensored-leak", "")
                    .replace("-chinese-subtitle", "");

                return avid2;
            }else {
                return null;
            }
        }
        return null;
    }


    //#endregion

    // ******************************************************************************************************************************************************
    //#region Other
	// 将XMLHttpRequest封装成fetch风格的函数
	function GM_fetch(url, options = {}) {
		return new Promise((resolve, reject) => {
			 GM_xmlhttpRequest({
				method: options.method || 'GET',
				url: url,
				headers: options.headers || {},
				data: options.body || null,
				responseType: options.responseType || 'text',
				timeout: options.timeout || 0,
			
				// 处理加载完成
				onload: function(response) {
					const fetchResponse = {
						ok: response.status >= 200 && response.status < 300,
						status: response.status,
						statusText: response.statusText,
						url: response.finalUrl || url,
						headers: response.responseHeaders,
						text: () => Promise.resolve(response.responseText),
						json: () => Promise.resolve(JSON.parse(response.responseText)),
						blob: () => Promise.resolve(new Blob([response.response])),
						arrayBuffer: () => Promise.resolve(response.response),
						clone: () => ({ ...fetchResponse })
					};
					resolve(fetchResponse);
				},
			
				// 处理错误
				onerror: function(error) {
					reject(new Error(`Network error: ${error}`));
				},
				
				// 处理超时
				ontimeout: function() {
					reject(new Error('请求超时'));
				}
			 });

		});
	}

	// 串行下载图片并保存到本地的函数
	async function downloadImagesSerially(imageUrls, progressCallback) {
		// 先下载第一张图片获取尺寸信息
		let sampleImg;
		try {
			const response = await GM_fetch(imageUrls[0], {
					method: 'GET',
					responseType: 'blob'
				});
			const imageBlob = await response.blob();
			sampleImg = await createImageFromBlob(imageBlob);
		} catch (error) {
			console.error('获取样本图片失败:', error);
			return;
		}
		
		// 计算切分部分的尺寸
		const partWidth = Math.floor(sampleImg.width / 6);
		const partHeight = Math.floor(sampleImg.height / 6);
		
		// 创建目标canvas
		const newCanvas = document.createElement('canvas');
		newCanvas.width = 6 * partWidth;
		newCanvas.height = imageUrls.length * partHeight;
		const ctx = newCanvas.getContext('2d');
		
		for (let imgIndex = 0; imgIndex < imageUrls.length; imgIndex++) {
			try {
				console.log(`正在下载第 ${imgIndex + 1}/${imageUrls.length} 张图片...`);
				progressCallback('image_start', imgIndex, imageUrls.length);
				
				// 使用fetch下载图片
				const response = await GM_fetch(imageUrls[imgIndex], {
					method: 'GET',
					responseType: 'blob'
				});
				
				if (!response.ok) {
					throw new Error(`HTTP错误! 状态码: ${response.status}`);
				}
				
				// 获取图片Blob
				const imageBlob = await response.blob();
				
				// // 生成文件名
				// // const fileName = `image_${imgIndex}_${Date.now()}.${getFileExtension(imageBlob.type)}`;
				// const fileName = `image_${imgIndex}.jpg`;
				
				// // 保存图片到本地
				// await saveImageToLocal(imageBlob, fileName);
				
				// 创建图片对象
				const img = await createImageFromBlob(imageBlob);
				
				// 切分图片
				// const imageParts = await splitImageIntoGrid(img, 6, 6);
				// 保存所有切分后的图片
				// for (let partIndex = 0; partIndex < imageParts.length; partIndex++) {
					// const partBlob = await canvasToBlob(imageParts[partIndex]);
					// const fileName = `image_${imgIndex}_part_${partIndex + 1}.jpg`;
					// await saveImageToLocal(partBlob, fileName);
					// console.log(`已保存切分图片: ${fileName}`);
				// }
				
				await splitAndDrawToCanvas(img, 6, 6, ctx, imgIndex, partWidth, partHeight);
				
				
				//console.log(`第 ${imgIndex} 张图片下载&处理完成`);
				progressCallback('image_progress', imgIndex, imageUrls.length);
				
			} catch (error) {
				console.error(`下载&处理 ${imageUrls[imgIndex]} 失败:`, error);
				// 绘制错误占位
				drawErrorPlaceholder(ctx, imgIndex, partWidth, partHeight);
			}
			
			// 添加延迟，避免请求过于频繁
			// if (imgIndex < imageUrls.length - 1) {
				// await delay(200);
			// }
		}
		
		// 保存重组后的图片
		try {
			const newImageBlob = await canvasToBlob(newCanvas);
			let avcode = getAVCode2();
			const fileName = `${avcode}_${imageUrls.length}x6.jpg`;
			await saveImageToLocal(newImageBlob, fileName);
			console.log(`重组图片保存完成: ${fileName}`);
			
		} catch (error) {
			console.error('重组图片保存失败:', error);
			progressCallback('image_error');
		}
		
		console.log('所有图片下载完成!');
		progressCallback('image_complate', imgIndex, imageUrls.length);
	}
	
	function delay(millisecond){
		new Promise(resolve => setTimeout(resolve, millisecond));
	}
	
	// 获取文件扩展名
	function getFileExtension(mimeType) {
		const extensions = {
			'image/jpeg': 'jpg',
			'image/jpg': 'jpg',
			'image/png': 'png',
			'image/gif': 'gif',
			'image/webp': 'webp',
			'image/svg+xml': 'svg'
		};
		return extensions[mimeType] || 'bin';
	}
	
	// 从Blob创建Image对象
	function createImageFromBlob(blob) {
		return new Promise((resolve, reject) => {
			const img = new Image();
			img.onload = () => resolve(img);
			img.onerror = reject;
			img.src = URL.createObjectURL(blob);
		});
	}

	// 将图片切分成rows x cols的网格
	async function splitImageIntoGrid(img, rows, cols) {
		const canvas = document.createElement('canvas');
		const ctx = canvas.getContext('2d');
		
		const partWidth = Math.floor(img.width / cols);
		const partHeight = Math.floor(img.height / rows);
		
		const imageParts = [];
		
		for (let row = 0; row < rows; row++) {
			//for (let col = 0; col < cols; col++) {
				let col = 0;
				// 创建每个切分部分的canvas
				const partCanvas = document.createElement('canvas');
				partCanvas.width = partWidth;
				partCanvas.height = partHeight;
				const partCtx = partCanvas.getContext('2d');
				
				// 计算源图像坐标
				const sx = col * partWidth;
				const sy = row * partHeight;
				
				// 绘制切分部分
				partCtx.drawImage(
					img,
					sx, sy, partWidth, partHeight, // 源图像区域
					0, 0, partWidth, partHeight    // 目标canvas区域
				);
				
				imageParts.push(partCanvas);
			//}
		}
		
		return imageParts;
	}
	
	// 切分和绘制函数
	async function splitAndDrawToCanvas(img, rows, cols, targetCtx, rowIndex, partWidth, partHeight) {
		// 创建临时canvas用于切分
		const tempCanvas = document.createElement('canvas');
		tempCanvas.width = partWidth;
		tempCanvas.height = partHeight;
		const tempCtx = tempCanvas.getContext('2d');
		
		// 计算源图片的实际切分尺寸（避免尺寸不匹配）
		const sourcePartWidth = Math.floor(img.width / cols);
		const sourcePartHeight = Math.floor(img.height / rows);
		
		for (let col = 0; col < cols; col++) {
			// 计算在目标canvas中的位置
			const destX = col * partWidth;
			const destY = rowIndex * partHeight;
			
			// 计算源图片中的位置（第一行的各部分）
			const sx = col * sourcePartWidth;
			const sy = 0; // 第一行
			
			// 清空临时canvas
			tempCtx.clearRect(0, 0, partWidth, partHeight);
			
			// 绘制切分部分到临时canvas
			tempCtx.drawImage(
				img,
				sx, sy, sourcePartWidth, sourcePartHeight, // 源区域
				0, 0, partWidth, partHeight                // 目标区域
			);
			
			// 绘制到目标canvas
			targetCtx.drawImage(tempCanvas, destX, destY);
		}
	}

	// 绘制错误占位
	function drawErrorPlaceholder(ctx, rowIndex, partWidth, partHeight) {
		for (let col = 0; col < 6; col++) {
			const x = col * partWidth;
			const y = rowIndex * partHeight;
			
			ctx.fillStyle = '#cccccc';
			ctx.fillRect(x, y, partWidth, partHeight);
			
			ctx.fillStyle = '#999999';
			ctx.font = '10px Arial';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			ctx.fillText('加载失败', x + partWidth / 2, y + partHeight / 2);
		}
	}

	// Canvas转换为Blob
	function canvasToBlob(canvas, quality = 0.3) {
		return new Promise((resolve) => {
			canvas.toBlob(resolve, 'image/jpg', quality);
		});
	}
	
	// 保存图片到本地
	function saveImageToLocal(blob, fileName) {
		return new Promise((resolve, reject) => {
			try {
				// 创建下载链接
				const url = URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = fileName;
				a.style.display = 'none';
				
				// 添加到文档并触发点击
				document.body.appendChild(a);
				a.click();
				
				// 清理
				setTimeout(() => {
					document.body.removeChild(a);
					URL.revokeObjectURL(url);
					resolve();
				}, 100);
				
			} catch (error) {
				reject(error);
			}
		});
	}
	
	// 将hh:mm:ss格式的时间转换为秒数
    function timeToSeconds(timeStr) {
        // 分割时间字符串
        const parts = timeStr.split(':');
        
        // 根据时间格式处理不同的情况
        if (parts.length === 3) {
            // hh:mm:ss格式
            const hours = parseInt(parts[0], 10);
            const minutes = parseInt(parts[1], 10);
            const seconds = parseInt(parts[2], 10);
            
            return hours * 3600 + minutes * 60 + seconds;
        } else if (parts.length === 2) {
            // mm:ss格式
            const minutes = parseInt(parts[0], 10);
            const seconds = parseInt(parts[1], 10);
            
            return minutes * 60 + seconds;
        } else if (parts.length === 1) {
            // 只有秒数格式
            return parseInt(parts[0], 10);
        } else {
            throw new Error('无效的时间格式');
        }
    }
	
	// 使用示例
	async function testCreateVideoFromImages() {
		try {
			console.log('开始下载图片并合成视频...');
			let playTimeEle = document.querySelector('.plyr__time--duration.plyr__time');
			if(!playTimeEle){
				console.log('播放时长获取失败！');
				return;
			}
			let playTimeStr = playTimeEle.textContent.trim();
			const playSeconds = timeToSeconds(playTimeStr);
			const imgNum = parseInt(playSeconds / 72);
			
			let imgEle= document.querySelector('.plyr__preview-thumb__image-container img');
			if(!imgEle){
				alert('请先激活预览框。。。');
				return;
			}
			const index = imgEle.src.indexOf('_');
			if (index == -1)  return;
			
			const imageUrls = [];
			let imgSrcBase = imgEle.src.substring(0, index);
			for(let i = 0; i <= imgNum; i++){
				imageUrls.push(imgSrcBase + '_' + i + '.jpg');
			}
			// "https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_0.jpg"
			
			const videoUrl = await downloadImagesSerially(imageUrls, function(type, current, total){
					switch (type) {
						case 'image_start':
							console.log(`开始处理图片 ${total}`);
							break;current
						case 'image_progress':
							console.log(`下载处理进度: ${current}/${total}。。。`);
							break;
						case 'image_complete':
							console.log(`完成图片 ${current}/${total}`);
							break;
						case 'image_error':
							console.error(`错误: ${current}`);
							break;
					}
			});
			console.log('视频合成完成:', videoUrl);
			
			
		} catch (error) {
			console.error('视频创建失败:', error);
			throw error;
		}
	}

    async function submitThumb(){
        try {
            // console.log('开始下载图片并合成视频...');
            // let playTimeEle = document.querySelector('.plyr__time--duration.plyr__time');
            // if(!playTimeEle){
                // console.log('播放时长获取失败！');
                // return;
            // }
            // let playTimeStr = playTimeEle.textContent.trim();
            // const playSeconds = timeToSeconds(playTimeStr);
			
			const playSeconds = player.duration;
			
            const picnum = player.config.thumbnail.pic_num;

            // let imgEle= document.querySelector('.plyr__preview-thumb__image-container img');
            // if(!imgEle){
                // alert('请先激活预览框。。。');
                // return;
            // }
			// let imgSrc = imgEle.src;
			let imgSrc = player.config.thumbnail.urls[0];
			
            const index = imgSrc.indexOf('_');
            if (index == -1)  return;
            let imgSrcBase = imgSrc.substring(0, index);

            let avcode = getAVCode2();

            sendSubmitRequest(avcode, imgSrcBase, playSeconds, picnum, function (res, data){
                if(res == 0){
                    alert("提交成功");
                }
            });

        } catch (error) {
            console.error('提交失败:', error);
            throw error;
        }
    }

    async function sendSubmitRequest(code, baseurl,playlength, picnum, callBack){
        // 使用 fetch 发送 GET 请求
        const url = `http://localhost:10168/thumb/submit?code=${code}&baseurl=${baseurl}&playlength=${playlength}&picnum=${picnum}`;
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return response.json();
            })
            .then(resultJson => {
                // 处理JSON数据
                if (resultJson.result == 0){
                    callBack(0, resultJson.data);
                    return;
                }
                throw new Error('request result faild');
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
                callBack(-1, null)
            });

    }

    //#endregion
	
	function guangGao(){
		// 拦截所有鼠标点击事件
		// document.addEventListener('mousedown', function(e) {
			// if (e.button === 0 || e.button === 2) { // 左右键均拦截
				// e.stopImmediatePropagation();
				// e.preventDefault();
				// return false;
			// }
		// }, true);
	}

})();